<?
//	*****************************************
//	SbSE metadata fetch component
//	v1.0.3 / 11.09.18
//	Required:
//	lib 0.9.1
//	*****************************************

require_once E.'_lib/_const.php';

class META {

	var $id_data;
	var $id_parent;
	var $assoc;
	var $data;
	var $varname;
	
	var $res;
	
	function META() {

		$this->data = array();
		$this->res = 255;
	}
	
	function init($id_data, $parent, $assoc='', $varname='') {

		$this->id_data = $id_data;
		$this->id_parent = $parent;
		$this->assoc = $assoc;
		$this->varname = $varname;
		
		$this->res = $this->fetch();
		return ! (bool) $this->res;
	}
	
	function fetch() {

//debug($this, 'meta', 1);
		
		if ($this->varname) {
			if ($d = datafetch('db_item', tb('data'),			// get records with empty 'assoc' (i.e. for all langs) or with corresponding 'assoc'
				"(id_data={$this->id_data}) AND
				(id_parent={$this->id_parent}) AND
				((assoc IS NULL) OR (assoc='') OR INSTR(assoc,'{$this->assoc}')!=0) AND
				(name='{$this->varname}')" )) {			// and specified variable name

//debug($d, 'meta-named', 1);
				switch($d['tag']) {

					case 1:		// data from list (list id: value, list assoc: assoc)
						$this->data = datafetch('db_list', array('table' => tb('list'), 
							'where' => "(id_list=".(int)$d['value'].") AND
										((assoc IS NULL) OR (assoc='') OR INSTR(assoc,'{$d[assoc]}')!=0)",
							'order' => 'id_index', 
							'index' => 'id'));
						break;
				
					case 0:		// plain data
					default:
						$this->data = $d['value'];
						return 0;
						break;
				}
			}
				else return 1;		// no such variable

		} else {		

			if ($d = datafetch_array('db_list', array('table' => tb('data'), 	// get records with empty 'assoc' (i.e. for all langs) or with corresponding 'assoc'
				'where' => "(id_data={$this->id_data}) AND
							(id_parent={$this->id_parent}) AND
							((assoc IS NULL) OR (assoc='') OR INSTR(assoc,'{$this->assoc}')!=0)" ))) {

//debug($d, 'meta-all', 1);
				foreach($d as $m) {
					switch($m['tag']) {
					
						case 1:		// data from list (list id: value, list assoc: assoc)
							$this->data[$m['name']] = datafetch('db_list', array('table' => tb('list'), 
								'where' => "(id_list=".(int)$m['value'].") AND
								((assoc IS NULL) OR (assoc='') OR INSTR(assoc,'{$m[assoc]}')!=0)",
								'order' => 'id_index', 'index' => 'id'));
							break;
							
						case 0:		// plain data
						default:
							$this->data[$m['name']] = $m['value'];
							break;
					}
				}
			
				return 0;
			}
		}
	}
}

?>